package com.xiaotu.spider.baidu.pipeline;

import com.xiaotu.common.model.StarBaikeBirthdayModel;
import com.xiaotu.common.model.StarModel;
import com.xiaotu.common.model.StarStringModel;
import com.xiaotu.common.util.*;
import com.xiaotu.spider.APipeline;
import com.xiaotu.storage.converter.AConverter;
import com.xiaotu.storage.converter.ConverterFactory;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;

import java.io.File;

@Component("StarBaikeBirthdayPipeline")
public class StarBaikeBirthdayPipeline extends APipeline
{
    private static final String[] STAR_BAIKE_INFO = new String[]{"starId", "starName", "status"};

    private static final String[] STAR_CONVERTER_BAIKE_INFO = new String[]{AConverter.STRING_CONVERT,
            AConverter.STRING_CONVERT, AConverter.INTEGER_CONVERT};

    private static final boolean[] STAR_THROW_BAIKE_INFO = new boolean[]{true, true, true};

    @Override
    protected void doProcess(ResultItems resultItems, Task task)
    {

        StarBaikeBirthdayModel model = resultItems.get(StarBaikeBirthdayModel.class.getName());
        if (model != null){
            String key = DataRedisKeyUtils.getKey(Constants.DataRedisKey.STAR_BAIKE_BIRTHDAY_YYYYMMDD);
            cacheHandler.hSet(key, model.getStarId(), model);
        }

        String filePath = resultItems.get("filePath");
        StarBaikeBirthdayModel starModel = resultItems.get(StarBaikeBirthdayModel.class.getName());
        if (starModel != null){
            FileUtil.writeFile(filePath + File.separator + "starBirthdayModel.csv", StringUtil.list2CSVLine
                    (ConverterFactory.convert(JSONObject.fromObject(starModel), STAR_BAIKE_INFO,
                            STAR_CONVERTER_BAIKE_INFO, STAR_THROW_BAIKE_INFO), SepratorUtil.SEP_PIPE) +
                    SepratorUtil.LINE_SEPRATOR);
        }

    }
}
